<template>
  <uni-file-picker
    v-model="fileLists"
    :mode="mode"
    :limit="limit"
    :title="title"
    :file-mediatype="fileMediatype"
    :disabled="disabled"
    @select="onSelect"
    @delete="onDelete"
  >
  </uni-file-picker>
</template>

<script>
import config from '@/common/config';
export default {
  data() {
    return {
      fileLists: [],
      disabled: false,
    };
  },
  props: {
    api: {
      type: String,
      default: '/resource/oss/upload',
    },
    mode: {
      type: String,
      default: 'list',
    },
    limit: {
      type: [String, Number],
      default: 9,
    },
    showTitle: {
      type: Boolean,
      default: true,
    },
    modelValue: {
      type: Array,
      default: () => [],
    },
    fileMediatype: {
      type: String,
      default: 'image',
    },
  },
  emits: ['del', 'update:modelValue'],
  watch: {
    modelValue: {
      handler(newVal) {
        if (newVal.length === 0) {
          this.fileLists = [];
        } else {
          this.fileLists = newVal;
        }
      },
      immediate: false,
      deep: true,
    },
  },
  computed: {
    title() {
      if (this.showTitle) {
        return `最多选择${this.limit}张图片`;
      } else {
        return '';
      }
    },
  },
  created() {},
  methods: {
    onSelect(e) {
      console.log('选择文件：', e);
      // loading提示
      uni.showLoading({ title: '上传中' });
      this.disabled = true;
      // 解决file对象取值问题
      // h5上传-需要文件file对象
      // const tempFilePaths = e.tempFiles[0].file;
      // 微信小程序上传-需要微信临时提供临时地址
      const tempFilePaths = e.tempFilePaths;
      tempFilePaths.map((item) => {
        uni.uploadFile({
          url: config.baseUrl + this.api,
          // 要上传文件对象-h5和微信小程序上传参数不一样只能存在一个
          // H5上传
          // file: tempFilePaths,
          // 微信小程序上传
          filePath: item,
          //文件对应的 key , 开发者在服务器端通过这个 key 可以获取到文件二进制内容
          name: 'file',
          // 请求头设置
          // 我们是需要token和用户id登录时存从uni-app数据存储中取
          header: {
            clientid: uni.getStorageSync('clientid'),
            authorization: `Bearer ${uni.getStorageSync('token')}`,
          },
          // 成功函数
          success: (res) => {
            // uni.uploadFile默认在外面包了一层data
            console.log('上传成功', res.data);
            // uni.uploadFile返回来的结果默认是JSON格式字符串，需要用JSON.parse转换成js对象
            console.log('上传数据转换', JSON.parse(res.data));
            // 取到文档服务器的值
            let uploadRes = JSON.parse(res.data);
            if (uploadRes.code === 200) {
              let x = {};
              // 下面3个值是uni-app规定的一个不能少
              if (typeof uploadRes.data === 'string') {
                x.url = e.tempFiles[0].url;
                x.name = e.tempFiles[0].name;
                x.extname = e.tempFiles[0].extname;
                x.ossId = uploadRes.data;
              } else {
                x.url = uploadRes.data.url;
                x.name = uploadRes.data.fileName;
                x.extname = e.tempFiles[0].extname || '';
                x.ossId = uploadRes.data.ossId;
              }
              this.fileLists.push(x);
              this.$emit('update:modelValue', this.fileLists);
              uni.showToast({ icon: 'none', title: '上传成功' });
            } else {
              uni.showToast({ icon: 'none', title: uploadRes.msg });
            }
          },
          // 失败提示用户重新上传
          fail: (error) => {
            console.log('失败', error);
            uni.showToast({ icon: 'none', title: '上传失败' });
          },
          complete: () => {
            this.disabled = false;
            uni.hideLoading();
          },
        });
      });
    },
    onDelete(e) {
      console.log('删除图片', e);
      this.$emit('del', e);
      this.fileLists.splice(e.index, 1);
    },
  },
};
</script>

<style lang="scss" scoped></style>
